import { getPage } from "@/api/photograph";
import type { Category } from "@/typings/";
import { isArray } from "lodash";
import { usePageStore } from "@/store";
import defaultImg from "@/assets/images/nana.webp";
// import EmptyError from "@/exceptions/EmptyException";
export async function useImage(
  currentPage: number = 1,
  pageSize: number = 10,
  search: string = "",
  count: number = 4,
  categoryID?: number,
) {
  const imgList = ref<any[]>([]);
  const imgInfo = ref<any[]>([]);
  const loading = ref(true);
  let width = computed(() => (totalWidth.value - (count + 1) * 20) / count);
  const totalWidth = ref(1000);
  const computedHeight = computed(() => {
    return Math.max(...imageHeight.value) + 20;
  });
  const computedWidth = computed(() => {
    return totalWidth.value;
  });
  const onPreload = (src: string, i: any, id: number) => {
    return new Promise((resolve, reject) => {
      let image = new Image();
      image.src = src;
      image.onload = function () {
        let height = image.height * (width.value / image.width);
        imgInfo.value.push({
          src: image.src,
          width: width,
          height: height,
          ...getPosition(i, height),
          id,
        });
        loading.value = false;
        resolve("load");
      };
      image.onerror = function () {
        reject("error");
      };
    });
  };
  const imageHeight = ref<number[]>(Array(count).fill(0));
  const getPosition = (i: number, height: number) => {
    if (i < count) {
      imageHeight.value[i] = height + 20;
      return {
        top: 10,
        left: (width.value + 20) * i + 20,
      };
    } else {
      let top = Math.min(...imageHeight.value);
      let index = 0;
      for (let n = 0; n < count; n++) {
        if (imageHeight.value[n] == top) {
          index = n;
          break;
        }
      }
      imageHeight.value[index] = top + height + 20;
      return {
        top: top + 10,
        left: (width.value + 20) * index + 20,
      };
    }
  };
  const loadImageList = async () => {
    imgList.value.splice(0);
    // try {
    let info = null;
    info = await getPage({ currentPage, pageSize, classification: search });
    if (info) {
      console.log(info);
      const page = usePageStore();
      page.setTotal(info.data.total);
      if (info.data && !isArray(info.data) && info.data.records.length) {
        info.data.records.forEach((item: any) => {
          imgList.value.push({
            src: item.url,
            id: item.pid,
          });
        });
      } else {
        ElMessage.error("查询不到,请刷新再去尝试");
        // throw new EmptyError("为空");
      }
      for (let i = 0; i < imgList.value.length; i++) {
        await onPreload(imgList.value[i].src, i, imgList.value[i].id);
      }
    } else {
      console.log("没有更多了");
    }
    // } catch (e) {
    //   console.log(e);
    // }
  };
  await loadImageList();
  return {
    imgInfo,
    computedHeight,
    computedWidth,
    loading,
  };
}
